package com.portal.sso.core.server.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import com.portal.sso.core.model.LineCaptchaModel;
import com.portal.sso.core.server.VerificationCodeServer;
import lombok.Getter;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @program: portal-sso
 * @description: 验证码实现类
 * @author: xuduo
 * @create: 2021-05-09 17:43
 * @Version: 1.0
 **/
public class VerificationCodeServerImpl implements VerificationCodeServer {
    final String BERIFICATION_CODE_PREFIX = "portal.sso.verification.code.";
    final int BERIFICATION_CODE_EXIT = 5;
    private StringRedisTemplate redisTemplate;
    @Getter
    private LineCaptchaModel lineCaptchaModel;

    public VerificationCodeServerImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public LineCaptchaModel createCaptcha(int w, int h, String uuid) {

        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(w, h);
//            String uuid = IdUtil.simpleUUID();
        LineCaptchaModel model = new LineCaptchaModel(lineCaptcha, uuid);
        this.lineCaptchaModel = model;
        getCode();
        return lineCaptchaModel;
    }

    @Override
    public String getCode() {
        if (this.lineCaptchaModel != null) {
            String code = lineCaptchaModel.getCaptcha().getCode();
                redisTemplate.opsForValue().set(BERIFICATION_CODE_PREFIX + this.lineCaptchaModel.getKey(), code, BERIFICATION_CODE_EXIT, TimeUnit.MINUTES);
            return code;
        }
        return null;
    }

    @Override
    public boolean verify(String key, String code) {
        if (redisTemplate.hasKey(BERIFICATION_CODE_PREFIX + key)) {
            String redis_code = redisTemplate.opsForValue().get(BERIFICATION_CODE_PREFIX + key);
            if (StrUtil.isNotEmpty(redis_code)) {
                return redis_code.equals(code);
            }
        }
        return false;
    }
}
